from datetime import datetime
from django.http import JsonResponse, HttpResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from . import serializers
from analyzer.statistics import services
from analyzer.exporters import excel as excel_exporter
import csv
import io


def parse_dt(s):
    if not s:
        return None
    try:
        return datetime.fromisoformat(s)
    except Exception:
        return None


class ProjectsCountView(APIView):
    def get(self, request):
        begin = parse_dt(request.GET.get('begin'))
        end = parse_dt(request.GET.get('end'))
        project_type = request.GET.get('type')
        region = request.GET.get('region')
        city = request.GET.get('city')
        industry = request.GET.get('industry')
        group_by = request.GET.get('group_by')
        if request.GET.get('use_precompute') == '1':
            data = services.projects_count_precomputed(begin, end, project_type, region, city, industry, group_by)
        else:
            data = services.projects_count(begin, end, project_type, region, city, industry, group_by)
        return Response({'status': 'success', 'code': 200, 'message': '查询成功', 'data': data})


class AmountBucketsView(APIView):
    def get(self, request):
        begin = parse_dt(request.GET.get('begin'))
        end = parse_dt(request.GET.get('end'))
        source = request.GET.get('source') or 'budget'
        region = request.GET.get('region')
        city = request.GET.get('city')
        industry = request.GET.get('industry')
        if request.GET.get('use_precompute') == '1':
            data = services.amount_buckets_precomputed(begin, end, source, region, city, industry)
        else:
            data = services.amount_buckets(begin, end, source, region, city, industry)
        return Response({'status': 'success', 'code': 200, 'message': '查询成功', 'data': data})


class CompanyWinRateView(APIView):
    def get(self, request):
        begin = parse_dt(request.GET.get('begin'))
        end = parse_dt(request.GET.get('end'))
        region = request.GET.get('region')
        city = request.GET.get('city')
        industry = request.GET.get('industry')
        if request.GET.get('use_precompute') == '1':
            data = services.company_win_rate_precomputed(begin, end, region, city, industry)
        else:
            data = services.company_win_rate(begin, end, region, city, industry)
        return Response({'status': 'success', 'code': 200, 'message': '查询成功', 'data': data})


class IndustryHHIView(APIView):
    def get(self, request):
        begin = parse_dt(request.GET.get('begin'))
        end = parse_dt(request.GET.get('end'))
        region = request.GET.get('region')
        city = request.GET.get('city')
        industry = request.GET.get('industry')
        if request.GET.get('use_precompute') == '1':
            data = services.industry_hhi_precomputed(begin, end, region, city, industry)
        else:
            data = services.industry_hhi(begin, end, region, city, industry)
        return Response({'status': 'success', 'code': 200, 'message': '查询成功', 'data': data})


class ExportView(APIView):
    def get(self, request, fmt: str):
        begin = parse_dt(request.GET.get('begin'))
        end = parse_dt(request.GET.get('end'))
        resource = request.GET.get('resource') or 'projects_count'
        region = request.GET.get('region')
        city = request.GET.get('city')
        industry = request.GET.get('industry')
        group_by = request.GET.get('group_by')
        if resource == 'projects_count':
            data = services.projects_count(begin, end, request.GET.get('type'), region, city, industry, group_by)
        elif resource == 'amount_buckets':
            data = services.amount_buckets(begin, end, request.GET.get('source') or 'budget', region, city, industry)
        elif resource == 'company_win_rate':
            data = services.company_win_rate(begin, end, region, city, industry)
        elif resource == 'industry_hhi':
            data = services.industry_hhi(begin, end, region, city, industry)
        else:
            return Response({'status': 'error', 'code': 400, 'message': '未知资源', 'data': []}, status=status.HTTP_400_BAD_REQUEST)
        if fmt == 'json':
            return Response({'status': 'success', 'code': 200, 'message': '导出成功', 'data': data})
        if fmt == 'csv':
            buf = io.StringIO()
            if isinstance(data, list) and data:
                writer = csv.DictWriter(buf, fieldnames=list(data[0].keys()))
                writer.writeheader()
                for row in data:
                    writer.writerow(row)
            resp = HttpResponse(buf.getvalue(), content_type='text/csv')
            resp['Content-Disposition'] = 'attachment; filename="analyzer.csv"'
            return resp
        if fmt == 'excel':
            content, filename = excel_exporter.export_list_dicts(data)
            resp = HttpResponse(content, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
            resp['Content-Disposition'] = f'attachment; filename="{filename}"'
            return resp
        return Response({'status': 'error', 'code': 400, 'message': '不支持的导出格式', 'data': []}, status=status.HTTP_400_BAD_REQUEST)
